package com.work.controller;


import com.google.gson.Gson;
import com.work.bean.Class;
import com.work.dao.ClassDao;
import com.work.dao.impl.ClassDaoImpl;
import com.work.service.ClassService;
import com.work.service.impl.ClassServiceImpl;
import com.work.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class ClassServlet extends BaseServlet{
    ClassService classService = new ClassServiceImpl();
    protected void queryClass(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        List<Class> classes = classService.queryClass();
        Gson gson=new Gson();
        String json=gson.toJson(classes);
        System.out.println(json);
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out=resp.getWriter();
        out.println(json);
    }
    protected void query(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        List<Class> classes = classService.queryClass();
        req.setAttribute("classes",classes);
        req.getRequestDispatcher("/pages/admin/class/admin_class.jsp").forward(req, resp);
    }
    protected void updateClass(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        Class aClass = WebUtils.copyParamToBean(req.getParameterMap(), new Class());
        classService.updateClass(aClass);
        resp.sendRedirect(req.getContextPath()+"/ClassServlet?action=query");
    }
    protected void deleteClass(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        classService.deleteClass(id);
        resp.sendRedirect(req.getContextPath()+"/ClassServlet?action=query");
    }
    protected void saveClass(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        Class aClass = WebUtils.copyParamToBean(req.getParameterMap(), new Class());
        classService.saveClass(aClass);
        resp.sendRedirect(req.getContextPath()+"/ClassServlet?action=query");
    }
    protected void queryClassById(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        Class c = classService.queryClassById(id);
        req.setAttribute("c",c);
        req.getRequestDispatcher("/pages/admin/class/admin_class_edit.jsp").forward(req, resp);
    }
}